// Service worker for Chrome extension
chrome.runtime.onInstalled.addListener(() => {
  console.log('Extension installed');
});

// Keep service worker alive
chrome.runtime.onStartup.addListener(() => {
  console.log('Extension starting up');
});

async function saveToMongoDB({ url, data, collection }) {
  try {
    const response = await fetch('http://localhost:3000/api/save', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        url,
        collection,
        data
      })
    });
    
    const result = await response.json();
    console.log('Save result:', result);
    return { success: true, insertedId: result.insertedId };
  } catch (error) {
    console.error('API error:', error);
    return { success: false, error: error.message };
  }
}

async function scrollPageToEnd(tab, scrollDelay = 200, pageEndDelay = 5000) {
  let scrollStatus;
  do {
    scrollStatus = await chrome.tabs.sendMessage(tab.id, { action: 'scrollPage' });
    await new Promise(resolve => setTimeout(resolve, scrollDelay));
  } while (scrollStatus?.status !== 'Scrolled to end');
  await new Promise(resolve => setTimeout(resolve, pageEndDelay));
}

async function extractAndSaveAmazonProductDetail(url, autoScroll = false) {
  try {
    const [tab] = await chrome.tabs.query({ active: true });
    if (autoScroll) {
      await scrollPageToEnd(tab, 200, 1000);
    }
    const data = await chrome.tabs.sendMessage(tab.id, { action: 'extractAmazonProductDetail' });
    const result = await saveToMongoDB({
      url: url,
      collection: 'amazon_product_detail',
      data: data.result
    });
    return { success: result.success, result };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

async function getAndOpenCurrentPageSearchResults() {
  const [tab] = await chrome.tabs.query({ active: true });
  
  // Get all search result links from content script
  const links = await chrome.tabs.sendMessage(tab.id, { 
    action: 'getAllSearchResultsLink' 
  });

  // Open each link in new tab with delay
  for (const link of links) {
    await chrome.tabs.create({ url: link, active: false });
    await new Promise(resolve => setTimeout(resolve, 1000)); // 1 second delay
  }
}

async function extractAndSaveOpenProducts(urlPattern, mongodbUrl, autoScroll = false) {
  const tabs = await chrome.tabs.query({
    url: urlPattern
  });
  
  const results = [];
  for (const tab of tabs) {
    // Activate the tab
    await chrome.tabs.update(tab.id, { active: true });
    
    // Call extractAndSaveProduct directly
    const result = await extractAndSaveAmazonProductDetail(mongodbUrl, autoScroll);
    
    results.push({
      tabId: tab.id,
      success: result.success,
      result: result.result
    });

    // Close the tab after successful extraction
    if (result.success) {
      await chrome.tabs.remove(tab.id);
    }
  }
  return results;
}

// Message handler
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'saveToMongoDB') {
    (async () => {
      try {
        const result = await saveToMongoDB(request);
        sendResponse({ success: result.success, result });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  // 处理消息extractAndSaveAmazonProductDetail
  else if (request.action === 'extractAndSaveAmazonProductDetail') {
    (async () => {
      const result = await extractAndSaveAmazonProductDetail(request.url, request.autoScroll);
      console.log('extractAndSaveAmazonProductDetail Result:', result);
      sendResponse(result);
    })();
    return true;
  }
  else if (request.action === 'extractAndSaveAllProducts') {
    (async () => {
      try {
        results = await extractAndSaveOpenProducts('https://www.amazon.com/*/dp/*/*', request.url, request.autoScroll);
        console.log('extractAndSaveAllProducts Results:', results);
        sendResponse({ success: true, results });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'openAllSearchResults') {
    (async () => {
      try {
        await getAndOpenCurrentPageSearchResults();

        sendResponse({ success: true });
      } catch (error) {
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'extractAllAmazonProductsFromListPages') { 
    (async () => {
      try {
        let remainingPages = request.numberOfPages > 0 ? request.numberOfPages : 1000; // Default to 1000 pages if not specified
        // Always start from list page
        const [start_tab] = await chrome.tabs.query({ active: true });
        const startUrl = start_tab.url.split('?')[0];

        let allResults = [];
        while (remainingPages > 0) {
          remainingPages--;

          await getAndOpenCurrentPageSearchResults();

          const results = await extractAndSaveOpenProducts('https://www.amazon.com/*/dp/*/*', request.url, request.autoScroll);
          allResults = allResults.concat(results);

          if (remainingPages > 0) {
            // Go to the list page
            const tabs = await chrome.tabs.query({ url: startUrl + '*' });
            const tab = tabs[0];
            await chrome.tabs.update(tab.id, { active: true });

            const switchPageResult = await chrome.tabs.sendMessage(tab.id, { action: 'switchPage' });
            if (switchPageResult?.status === 'Switched to end') {
              break;
            }
            await new Promise(resolve => setTimeout(resolve, 5000));
          }
        }
        
        sendResponse({ success: true, result: allResults });
      } catch (error) {
        console.log('extractAllFastmossProductsFromList Error:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }
  else if (request.action === 'getAllReviewColorSizes') {
    (async () => { 
      const [tab] = await chrome.tabs.query({ active: true });
      let allColorSizes = []

      while (true) {
        const result = await chrome.tabs.sendMessage(tab.id, { 
          action: 'getAllReviewColorSizes'
        });

        if (result?.success) {
          allColorSizes = [...allColorSizes, ...result.result];
        } else {
          console.log('All Review ColorSizes done!', allColorSizes)
          // The save all tests in allColorSizes into system clipboard
          await chrome.tabs.sendMessage(tab.id, { action: 'copyToClipboard', text: allColorSizes.join('\n') });

          break;
        }
        // Wait for new page to load
        await new Promise(resolve => setTimeout(resolve, 3000));
      }
      sendResponse({ success: true, result: allColorSizes });
    })();
    return true;
  }
});
